document.addEventListener('DOMContentLoaded', function() {
    const header = document.querySelector('.header');
    if (!header) {
        console.error('未找到header元素');
        return;
    }
    let headerOffsetBottom = 0;
    let isFixed = false;
    let originalPosition = getComputedStyle(header).position;
    let originalTop = getComputedStyle(header).top;
    let originalLeft = getComputedStyle(header).left;
    let originalWidth = getComputedStyle(header).width;

    function calculateHeaderOffset() {
        const rect = header.getBoundingClientRect();
        headerOffsetBottom = rect.top + rect.height + window.scrollY;
    }

    function handleScroll() {
        const scrollY = window.scrollY;       
        if (scrollY >= headerOffsetBottom && !isFixed) {
            
            header.classList.add('header-fixed');
            header.style.position = 'fixed';
            header.style.top = '0';
            header.style.left = '0';
            header.style.width = '100%';
         
            document.querySelector('.img0').style.display = 'none';
            document.querySelector('.img1').style.display = 'block';
            document.querySelectorAll('.two').forEach(item => {
                item.style.color = '#000';
            });
            isFixed = true;
        } else if (scrollY < headerOffsetBottom && isFixed) {
            
            header.classList.remove('header-fixed');
            header.style.position = originalPosition;
            header.style.top = originalTop;
            header.style.left = originalLeft;
            header.style.width = originalWidth;
           
            document.querySelector('.img1').style.display = 'none';
            document.querySelector('.img0').style.display = 'block';
            document.querySelectorAll('.two').forEach(item => {
                item.style.color = '#fff';
            });
            isFixed = false;
        }
    }

    calculateHeaderOffset();
    handleScroll();  
    let scrollTimeout;
    window.addEventListener('scroll', function() {
        clearTimeout(scrollTimeout);
        scrollTimeout = setTimeout(handleScroll, 10);
    });
    window.addEventListener('resize', calculateHeaderOffset);
    window.addEventListener('load', calculateHeaderOffset);
});


function formatNumber(num) {
    // 处理null或undefined的情况
    if (!num && num !== 0) return '0';
    
    // 处理亿级
    if (num >= 100000000) {
        return (num / 100000000).toFixed(2) + '亿';
    }
    // 处理万级
    else if (num >= 10000) {
        return (num / 10000).toFixed(0) + '万';
    }
    // 其他情况保留整数
    return Math.round(num).toString();
}

const bookContainer = document.querySelector('.books');
const listContainer = document.querySelector('.main-lisy');
let carouselInterval; // 用于存储轮播定时器
let currentIndex = 0; // 当前显示的书籍索引
let allBooks = []; // 存储所有书籍数据

// 初始化UI显示加载状态
bookContainer.innerHTML = '<div class="loading">加载中...</div>';
listContainer.innerHTML = '<div class="loading">加载中...</div>';

fetch('https://naodongapi.zongheng.com/planet/recommendations?uniqCharId=NAODONG_BIG_COVERS__0')
    .then(res => {
        if (!res.ok) {
            throw new Error(`HTTP错误，状态码: ${res.status}`);
        }
        return res.json();
    })
    .then(data => {
        const result = data.result;
        
        // 存储书籍数据供轮播使用
        allBooks = result.heads || [];
        
        // 渲染头部书籍信息
        renderBooksSection(allBooks);
        
        // 渲染尾部列表信息
        renderListSection(result.tails);
        
        // 启动自动轮播
        startCarousel();
    })
    .catch(err => {
        console.error('获取数据失败:', err);
        bookContainer.innerHTML = '<div class="error">加载失败，请稍后重试</div>';
        listContainer.innerHTML = '<div class="error">加载失败，请稍后重试</div>';
    });

// 渲染头部书籍区域
function renderBooksSection(books) {
    if (!books || books.length === 0) {
        bookContainer.innerHTML = '<div class="no-data">暂无书籍数据</div>';
        return;
    }
    
    // 初始显示第一本书
    updateBookDetail(books[0]);
}

// 更新书籍详情
function updateBookDetail(currentBook) {
    // 生成缩略图
    let thumbnails = '';
    allBooks.forEach((book, index) => {
        thumbnails += `
            <img 
                src="${book.coverUrl}" 
                alt="${book.title || '书籍封面'}" 
                data-index="${index}"
                class="thumbnail ${currentIndex === index ? 'active' : ''}"
            >
        `;
    });
    
    // 更新主内容区
    bookContainer.innerHTML = `
        <div class="books-detail"> 
            <div class="books-detail--top">
                <div class="top-img">
                    <div class="top-img--cover"> 
                        <img src="${currentBook.coverUrl}" alt="${currentBook.title || '书籍封面'}">
                    </div>
                </div>
                <div class="top-book-detail">
                    <div class="detail-top"><span class="global-hover">${currentBook.title || '未知书名'}</span></div>
                    <div class="detail-top1">
                        <div class="auther">作者<span class="auther1" onclick="diji()">${currentBook.authorName || '未知作者'}</span></div>
                        <div class="num">字数<span class="num1">${formatNumber(currentBook.wordCount)}</span></div>
                    </div>
                    <div class="desc">${currentBook.summary || '暂无简介'}</div>
                    <div class="desc1">
                        <div class="n">最新章节</div>
                        <span>${currentBook.newestChapter?.title || '暂无章节信息'}</span>
                    </div>
                </div>
            </div>
            <div class="books-detail--bottom">
                <div class="bottom-img">
                    ${thumbnails}
                </div>
                <div class="bottom-read-btn">
                    <div class="anim"></div>
                    <span>立即阅读</span>
                </div>
            </div>
        </div>
    `;
    
    // 为缩略图添加鼠标事件
    document.querySelectorAll('.thumbnail').forEach(thumb => {
        // 鼠标悬停时切换书籍并暂停轮播
        thumb.addEventListener('mouseenter', function() {
            const index = parseInt(this.getAttribute('data-index'));
            if (index !== currentIndex) {
                currentIndex = index;
                updateBookDetail(allBooks[currentIndex]);
                pauseCarousel();
            }
        });
        
        // 鼠标离开缩略图区域时恢复轮播
        thumb.addEventListener('mouseleave', function() {
            startCarousel();
        });
    });
}

// 渲染列表区域
function renderListSection(items) {
    if (!items || items.length === 0) {
        listContainer.innerHTML = '<div class="no-data">暂无推荐数据</div>';
        return;
    }
    
    let listHtml = '';
    items.forEach(item => {
        listHtml += `
            <div class="lisy1">
                <div class="lisy-img">
                    <img src="${item.coverUrl}" alt="${item.bookName || '书籍封面'}">
                </div>
                <div class="lisy-content">
                    <div class="content-title">
                        <span  onclick="ju()">${item.bookName || '未知书名'}</span>
                    </div>
                    <div class="lisy-desc">${item.description || '暂无描述'}</div>
                </div>
                <img class="list-item--img-fix" 
                     src="https://revo.zongheng.com/naodong/2024/images/446dcc9.png" 
                     alt="装饰图标">
            </div>
        `;
    });
    
    listContainer.innerHTML = listHtml;
}

// 启动自动轮播
function startCarousel() {
    // 先清除已有的定时器，避免重复创建
    if (carouselInterval) {
        clearInterval(carouselInterval);
    }
    
    // 每3秒切换一次（3000毫秒）
    carouselInterval = setInterval(() => {
        // 计算下一个索引，实现无限循环
        currentIndex = (currentIndex + 1) % allBooks.length;
        updateBookDetail(allBooks[currentIndex]);
    }, 3000);
}

// 暂停轮播
function pauseCarousel() {
    if (carouselInterval) {
        clearInterval(carouselInterval);
        carouselInterval = null;
    }
}

// 当鼠标悬停在整个书籍展示区域时暂停轮播
bookContainer.addEventListener('mouseenter', pauseCarousel);
// 当鼠标离开整个书籍展示区域时恢复轮播
bookContainer.addEventListener('mouseleave', startCarousel);


const wrapper =document.querySelector('.swiper-wrapper')
axios.post('https://www.zongheng.com/api2/catefine/storeSearch', {
}).then(res=> {
    // console.log(res.data.result.bookList)
    for(let i=0;i<8;i++){
        wrapper.innerHTML+=`
            <div class="swiper-slide"  onclick="ju()">
            <img src="${res.data.result.bookList[i].picUrl}" >
            <div class="lines">${res.data.result.bookList[i].name}</div>
            </div>
        `
    }
      var swiper = new Swiper('.swiper-container', {
        pagination: '.swiper-pagination',
        nextButton: '.swiper-button-next',
        prevButton: '.swiper-button-prev',
        paginationClickable: true,
        spaceBetween: 50,
        centeredSlides: true,
        autoplay: 2500,
        autoplayDisableOnInteraction: false,
        loop:true,
        slidesPerView: 7,
        onSlideChangeEnd: function(swiper) {
    swiper.slides.removeClass('swiper-slide-active');
    swiper.slides.eq(swiper.activeIndex).addClass('swiper-slide-active');
  }
    });
}).catch(err=> {
    console.log(err)
})


const news=document.querySelector('.news-main')
axios.post('https://www.zongheng.com/api2/catefine/storeSearch', {
    worksTypes: 0,
bookType: 0,
subWorksTypes: 0,
totalWord: 0,
serialStatus: 1,
vip: 0,
naodongFilter: 1,
categoryId: 0,
categoryPid: 0
}).then(res=> {
    // console.log(res.data.result.bookList)
    const newss=res.data.result.bookList
    for(let i=0;i<9;i++){
       news.innerHTML+=`
            <div class="news-box">
                    <img src="${newss[i].picUrl}" alt=""  onclick="ju()">
                    <div class="news-text-box">
                        <div class="news-text" onclick="ju()">${newss[i].name}</div>
                        <div class="text1">
                        <span>${newss[i].cateFineName}</span>
                        <span  onclick="diji()">${newss[i].authorName}</span></div>
                    </div>
                </div>
        `
    }
    }).catch(err=> {
    console.log(err)
})

document.addEventListener('DOMContentLoaded', function() {
    const mains = document.querySelector('.hots-main');
    let activeElement = null; // 跟踪当前激活的元素
    const dayBtn = document.querySelector('.days'); // 日按钮
    const monthBtn = document.querySelector('.mous'); // 月按钮
    
    // 定义两个接口地址
    const urls = {
        day: 'https://naodongapi.zongheng.com/planet/ranks?pageNum=1&pageSize=10&isFavorite=1&rankType=3&periodType=0',
        month: 'https://naodongapi.zongheng.com/planet/ranks?pageNum=1&pageSize=10&isFavorite=1&rankType=3&periodType=2'
    };
    
    // 初始加载日数据，并设置初始类名状态
    loadData(urls.day);
    dayBtn.classList.add('days1'); // 初始状态给日按钮添加days1类
    monthBtn.classList.remove('days1'); // 确保月按钮初始没有days1类
    
    // 绑定按钮点击事件
    dayBtn.addEventListener('click', () => {
        // 点击日按钮：给自己加days1，移除月按钮的days1
        dayBtn.classList.add('days1');
        monthBtn.classList.remove('days1');
        // 加载日数据
        loadData(urls.day);
    });
    
    monthBtn.addEventListener('click', () => {
        // 点击月按钮：给自己加days1，移除日按钮的days1
        monthBtn.classList.add('days1');
        dayBtn.classList.remove('days1');
        // 加载月数据
        loadData(urls.month);
    });
    
    // 加载数据的函数
    function loadData(url) {
        fetch(url)
            .then(res => res.json())
            .then(res1 => {
                // console.log('加载数据:', res1.result.items);
                const items = res1.result.items;
                
                // 清空容器
                mains.innerHTML = '';
                
                // 生成列表项
                items.forEach((item, index) => {
                    mains.innerHTML += `
                        <div class="main-line">
                            <div class="line-one">
                                <span>${index + 1}</span>
                                <div class="one"  onclick="ju()" >${item.bookName}</div>
                            </div>
                            <div class="line-two">
                                <div>${index + 1}</div>
                                <div class="line-two-name">
                                    <div class="two2" onclick="ju()">${item.bookName}</div>
                                    <div class="name"  onclick="diji()">${item.authorName}</div>
                                </div>
                                <div>
                                    <img src="${item.coverUrl}" alt="${item.bookName}的封面">
                                </div>
                            </div>
                        </div>
                    `;
                });
                
                // 获取所有main-line元素
                const mainLines = document.querySelectorAll('.main-line');
                
                // 初始化显示状态
                initDisplay(mainLines);
                
                // 绑定事件
                bindEvents(mainLines);
            })
            .catch(err => {
                console.log('获取数据出错:', err);
            });
    }
    
    // 初始化显示状态
    function initDisplay(elements) {
        elements.forEach((el, index) => {
            const lineOne = el.querySelector('.line-one');
            const lineTwo = el.querySelector('.line-two');
            
            if (index === 0) {
                // 初始状态：第一个显示line-two
                lineOne.style.display = 'none';
                lineTwo.style.display = 'flex';
                activeElement = el; // 设置初始激活元素
            } else {
                // 其他元素默认显示line-one
                lineOne.style.display = 'flex';
                lineTwo.style.display = 'none';
            }
        });
    }
    
    // 绑定鼠标事件
    function bindEvents(elements) {
        elements.forEach(el => {
            // 鼠标进入元素
            el.addEventListener('mouseenter', () => {
                // 如果有激活元素且不是当前元素，则将其切换为line-one
                if (activeElement && activeElement !== el) {
                    activeElement.querySelector('.line-one').style.display = 'flex';
                    activeElement.querySelector('.line-two').style.display = 'none';
                }
                
                // 当前元素切换为line-two
                el.querySelector('.line-one').style.display = 'none';
                el.querySelector('.line-two').style.display = 'flex';
                
                // 更新激活元素
                activeElement = el;
            });
            
            // 鼠标离开元素
            el.addEventListener('mouseleave', (e) => {
                // 检查鼠标是否移到了其他main-line元素
                const isMovingToAnotherLine = Array.from(elements).some(line => 
                    line !== el && line.contains(e.relatedTarget)
                );
                
                // 如果不是移到其他main-line元素（即移出到区域外）
                if (!isMovingToAnotherLine) {
                    // 保持当前元素的line-two显示
                    el.querySelector('.line-one').style.display = 'none';
                    el.querySelector('.line-two').style.display = 'flex';
                    // 保持当前元素为激活状态
                    activeElement = el;
                }
                // 如果移到其他main-line，由目标元素的mouseenter处理
            });
        });
    }
});

 document.addEventListener('DOMContentLoaded', () => {
            const carousel = document.getElementById('carousel');
            const items = document.querySelectorAll('.carousel-item');
            const title = document.getElementById('title');
            const author = document.getElementById('author');
            const intro = document.getElementById('intro');
            const prevBtn = document.querySelector('.prev-btn');
            const nextBtn = document.querySelector('.next-btn');
            const indicators = document.querySelectorAll('.indicator');
            const itemCount = items.length;
            let currentIndex = 0;
            let interval;
            
            // 存储每张图片对应的下方内容
            const contentData = [
                {
                    title: "问鼎：重生后我权势滔天",
                    author: "睡秋",
                    intro: "又名《最强骚浪贱系统》、《开局：我掳走了宗主的芳心》，觉醒骚王系统，泡最美的妞，耍最大的宝剑，放最狂野的话，走最风骚的步伐！“什么，他是天才妖孽？”“十个，老子要打十个！”“什么，群战？”“和我大威天龙拼，你有这个实力么？！”"
                },
                {
                    title: "武道至尊：开局获得洪荒血脉",
                    author: "乘风",
                    intro: "身怀洪荒血脉，脚踏九天之上！少年林辰，自微末中崛起，凭借神秘传承，一路横扫天下，战遍诸天强者，终成一代武道至尊！"
                },
                {
                    title: "都市狂医：我的病人有点猛",
                    author: "夜无声",
                    intro: "退役特种兵回归都市，成为一名小医生，却不料招惹了各路大佬。美女总裁、江湖大佬、神秘组织... 他的病人一个比一个猛！"
                }
            ];
            
            // 定义位置类名
            const positions = ['center', 'right', 'left'];
            
            // 更新轮播状态
            function updateCarousel() {
                // 移除所有位置类
                items.forEach(item => {
                    positions.forEach(pos => item.classList.remove(pos));
                });
                
                // 为每个项目添加新的位置类
                items.forEach((item, index) => {
                    // 计算每个项目应该处于的位置
                    const positionIndex = (index - currentIndex + itemCount) % itemCount;
                    item.classList.add(positions[positionIndex]);
                    item.dataset.index = index;
                });
                
                // 更新内容
                updateContent(currentIndex);
                
                // 更新指示器
                updateIndicators();
            }
            
            // 更新内容
            function updateContent(index) {
                // 添加淡入效果
                const contentContainer = document.querySelector('.le-main-md');
                contentContainer.style.opacity = '0';
                
                setTimeout(() => {
                    title.textContent = contentData[index].title;
                    author.textContent = contentData[index].author;
                    intro.textContent = contentData[index].intro;
                    contentContainer.style.opacity = '1';
                }, 300);
            }
            
            // 更新指示器
            function updateIndicators() {
                indicators.forEach((indicator, index) => {
                    if (index === currentIndex) {
                        indicator.classList.add('active');
                    } else {
                        indicator.classList.remove('active');
                    }
                });
            }
            
            // 切换到下一张
            function nextSlide() {
                currentIndex = (currentIndex + 1) % itemCount;
                updateCarousel();
            }
            
            // 切换到上一张
            function prevSlide() {
                currentIndex = (currentIndex - 1 + itemCount) % itemCount;
                updateCarousel();
            }
            
            // 自动播放
            function startAutoPlay() {
                interval = setInterval(nextSlide, 5000); // 每5秒切换一次
            }
            
            // 初始化
            updateCarousel();
            startAutoPlay();
            
            // 点击图片切换
            items.forEach(item => {
                item.addEventListener('click', () => {
                    const index = parseInt(item.dataset.index);
                    if (index !== currentIndex) {
                        clearInterval(interval);
                        currentIndex = index;
                        updateCarousel();
                        startAutoPlay();
                    }
                });
            });
            // 鼠标悬停暂停自动播放
            carousel.parentElement.addEventListener('mouseenter', () => {
                clearInterval(interval);
            });
            
            // 鼠标离开恢复自动播放
            carousel.parentElement.addEventListener('mouseleave', () => {
                startAutoPlay();
            });
        });


        const mdtp=document.querySelector('.md-main-top')
        const mdbo=document.querySelector('.md-ma-bob')
axios.post('https://www.zongheng.com/api2/catefine/storeSearch', {
    worksTypes: 0,
bookType: 0,
subWorksTypes: 0,
totalWord: 0,
serialStatus: 9,
vip: 0,
naodongFilter: 1,
categoryId: 0,
categoryPid: 0
}).then(res=> {
    // console.log(res.data.result.bookList)
   const list=res.data.result.bookList
   for(let i=0;i<7;i++){
    if(i<4){
        mdtp.innerHTML+=`
            <div class="top-box">
                        <img src="${list[i].picUrl}" alt=""  onclick="ju()">
                        <div class="tp-bx-ti" onclick="ju()">${list[i].name}</div>
                        <div class="tp-bx-nm"  onclick="diji()">${list[i].authorName}</div>
                    </div>
        `
    }else{
        mdbo.innerHTML+=`
            <div class="md-ma-bo">
                    <img class="img-yy" src="${list[i].picUrl}" alt=""  onclick="ju()">
                    <div class="ma-bo-md">
                        <div class="md-tp"  onclick="ju()">${list[i].name}</div>
                        <div class="md-bo">${list[i].description}</div>
                    </div>
                    <img class="img-icon" src="img/13.png" alt="">
                </div>
        `

    }
   }
    }).catch(err=> {
    console.log(err)
})

 document.addEventListener('DOMContentLoaded', function() {
    const mains = document.querySelector('.fin-main');
    let activeElement = null; // 跟踪当前激活的元素
    
    // 定义完结榜接口地址
    const url = 'https://naodongapi.zongheng.com/planet/ranks?pageNum=1&pageSize=10&isFavorite=1&rankType=9';
    
    // 初始加载完结榜数据
    loadData(url);
    
    // 加载数据的函数
    function loadData(url) {
        fetch(url)
            .then(res => res.json())
            .then(res1 => {
                // console.log('加载完结榜数据:', res1.result.items);
                const items = res1.result.items;
                
                // 清空容器
                mains.innerHTML = '';
                
                // 生成列表项：循环创建10个main-line
                items.forEach((item, index) => {
                    mains.innerHTML += `
                        <div class="main-line1" data-index="${index}"> <!-- 添加data-index便于定位 -->
                            <div class="line-one1">
                                <span>${index + 1}</span>
                                <div class="one1">${item.bookName}</div>
                            </div>
                            <div class="line-two1">
                                <div>${index + 1}</div>
                                <div class="line-two-name1">
                                    <div class="two21" onclick="ju()" >${item.bookName}</div>
                                    <div class="name1"  onclick="diji()">${item.authorName}</div>
                                </div>
                                <div>
                                    <img src="${item.coverUrl}" alt="${item.bookName}的封面">
                                </div>
                            </div>
                        </div>
                    `;
                });
                
                // 获取所有main-line元素
                const mainLines = document.querySelectorAll('.main-line1');
                
                // 初始化显示状态：直接定位第一个元素，无需复杂判断
                initDisplay(mainLines);
                
                // 绑定鼠标事件
                bindEvents(mainLines);
            })
            .catch(err => {
                console.log('获取完结榜数据出错:', err);
            });
    }
    
    // 初始化显示状态：仅确保第一个元素的line-two正常显示（依赖CSS默认样式）
  function initDisplay(elements) {
        elements.forEach((el, index) => {
            const lineOne = el.querySelector('.line-one1');
            const lineTwo = el.querySelector('.line-two1');
            
            if (index === 0) {
                // 初始状态：第一个显示line-two
                lineOne.style.display = 'none';
                lineTwo.style.display = 'flex';
                activeElement = el; // 设置初始激活元素
            } else {
                // 其他元素默认显示line-one
                lineOne.style.display = 'flex';
                lineTwo.style.display = 'none';
            }
        });
    }
    
    // 绑定鼠标事件：保持原有逻辑，仅在鼠标交互时切换显示
    function bindEvents(elements) {
        elements.forEach(el => {
            // 鼠标进入：当前元素显示line-two，其他显示line-one
            el.addEventListener('mouseenter', () => {
                if (activeElement && activeElement !== el) {
                    // 其他元素：显示line-one，隐藏line-two
                    activeElement.querySelector('.line-one1').style.display = 'flex';
                    activeElement.querySelector('.line-two1').style.display = 'none';
                }
                // 当前元素：显示line-two，隐藏line-one
                el.querySelector('.line-one1').style.display = 'none';
                el.querySelector('.line-two1').style.display = 'flex';
                
                // 更新激活元素
                activeElement = el;
            });
            
            // 鼠标离开：如果未移到其他列表项，保持当前元素line-two显示
            el.addEventListener('mouseleave', (e) => {
                const isMovingToAnotherLine = Array.from(elements).some(line => 
                    line !== el && line.contains(e.relatedTarget)
                );
                
                if (!isMovingToAnotherLine) {
                    el.querySelector('.line-one1').style.display = 'none';
                    el.querySelector('.line-two1').style.display = 'flex';
                    activeElement = el;
                }
            });
        });
    }
});


const man=document.querySelector('.man-main')
axios.post('https://www.zongheng.com/api2/catefine/storeSearch', {
    worksTypes: 0,
bookType: 0,
subWorksTypes: 0,
totalWord: 0,
serialStatus: 7,
vip: 0,
naodongFilter: 1,
categoryId: 0,
categoryPid: 0
}).then(res=> {
    // console.log(res.data.result.bookList)
    const mans=res.data.result.bookList
    for(let i=0;i<9;i++){
       man.innerHTML+=`
            <div class="man-box">
                    <img src="${mans[i].picUrl}" alt="" onclick="ju()" >
                    <div class="man-text-box">
                        <div class="man-text" onclick="ju()">${mans[i].name}</div>
                        <div class="text1">
                        <span>${mans[i].cateFineName}</span>
                        <span  onclick="diji()">${mans[i].authorName}</span></div>
                    </div>
                </div>
        `
    }
    }).catch(err=> {
    console.log(err)
})




document.addEventListener('DOMContentLoaded', function() {
    const mainss = document.querySelector('.dj-main');
    let activeElement = null; // 跟踪当前激活的元素
    
    // 定义完结榜接口地址
    const url = 'https://naodongapi.zongheng.com/planet/ranks?pageNum=1&pageSize=10&isFavorite=1&rankType=0';
    
    // 初始加载完结榜数据
    loadData(url);
    
    // 加载数据的函数
    function loadData(url) {
        fetch(url)
            .then(res => res.json())
            .then(res1 => {
                // console.log('加载完结榜数据:', res1.result.items);
                const itemss = res1.result.items;
                
                // 清空容器
                mainss.innerHTML = '';
                
                // 生成列表项：循环创建10个main-line
                itemss.forEach((item, index) => {
                    mainss.innerHTML += `
                        <div class="main-line11" data-index="${index}"> <!-- 添加data-index便于定位 -->
                            <div class="line-one11">
                                <span>${index + 1}</span>
                                <div class="one11">${item.bookName}</div>
                            </div>
                            <div class="line-two11">
                                <div>${index + 1}</div>
                                <div class="line-two-name11">
                                    <div class="two211"  onclick="ju()">${item.bookName}</div>
                                    <div class="name11"  onclick="diji()">${item.authorName}</div>
                                </div>
                                <div>
                                    <img src="${item.coverUrl}" alt="${item.bookName}的封面">
                                </div>
                            </div>
                        </div>
                    `;
                });
                
                // 获取所有main-line元素
                const mainLines = document.querySelectorAll('.main-line11');
                
                // 初始化显示状态：直接定位第一个元素，无需复杂判断
                initDisplay(mainLines);
                
                // 绑定鼠标事件
                bindEvents(mainLines);
            })
            .catch(err => {
                console.log('获取完结榜数据出错:', err);
            });
    }
    
    // 初始化显示状态：仅确保第一个元素的line-two正常显示（依赖CSS默认样式）
  function initDisplay(elements) {
        elements.forEach((el, index) => {
            const lineOne = el.querySelector('.line-one11');
            const lineTwo = el.querySelector('.line-two11');
            
            if (index === 0) {
                // 初始状态：第一个显示line-two
                lineOne.style.display = 'none';
                lineTwo.style.display = 'flex';
                activeElement = el; // 设置初始激活元素
            } else {
                // 其他元素默认显示line-one
                lineOne.style.display = 'flex';
                lineTwo.style.display = 'none';
            }
        });
    }
    
    // 绑定鼠标事件：保持原有逻辑，仅在鼠标交互时切换显示
    function bindEvents(elements) {
        elements.forEach(el => {
            // 鼠标进入：当前元素显示line-two，其他显示line-one
            el.addEventListener('mouseenter', () => {
                if (activeElement && activeElement !== el) {
                    // 其他元素：显示line-one，隐藏line-two
                    activeElement.querySelector('.line-one11').style.display = 'flex';
                    activeElement.querySelector('.line-two11').style.display = 'none';
                }
                // 当前元素：显示line-two，隐藏line-one
                el.querySelector('.line-one11').style.display = 'none';
                el.querySelector('.line-two11').style.display = 'flex';
                
                // 更新激活元素
                activeElement = el;
            });
            
            // 鼠标离开：如果未移到其他列表项，保持当前元素line-two显示
            el.addEventListener('mouseleave', (e) => {
                const isMovingToAnotherLine = Array.from(elements).some(line => 
                    line !== el && line.contains(e.relatedTarget)
                );
                
                if (!isMovingToAnotherLine) {
                    el.querySelector('.line-one11').style.display = 'none';
                    el.querySelector('.line-two11').style.display = 'flex';
                    activeElement = el;
                }
            });
        });
    }
});

const a=document.querySelector('.arae-main')
axios.post('https://www.zongheng.com/api2/catefine/storeSearch', {
    worksTypes: 0,
    bookType: 0,
    subWorksTypes: 0,
    totalWord: 6,
    serialStatus: 1,
    vip: 0,
    naodongFilter: 1,
    categoryId: 0,
    categoryPid: 0
}).then(res=> {
    // console.log(res.data.result.bookList)
    const nn=res.data.result.bookList
    a.innerHTML = '';
    for(let i=0;i<5;i++){  
        a.innerHTML+=`
            <div class="arae-box">
                    <div class="arae-box1">
                        <div class="area-ti">${nn[i].name}</div>
                        <div class="arae-dsc">${nn[i].description}</div>
                    </div>
                    <div class="arae-box2">
                        <img src="${nn[i].picUrl}" alt=""  onclick="ju()">
                        <div class="arae-md">
                            <div class="arae-md1"  onclick="ju()">${nn[i].name}</div>
                            <div class="arae-md2">${nn[i].description}</div>
                        </div>
                    </div>
                </div> 
        `
    }
    const boxa= document.querySelectorAll('.arae-box');
            
            // 初始状态：第一个元素显示arae-box2，隐藏arae-box1
            if(boxa.length > 0) {
                boxa[0].querySelector('.arae-box1').style.display = 'none';
                boxa[0].querySelector('.arae-box2').style.display = 'flex';
            }
            
            // 为每个元素添加鼠标悬停事件
            boxa.forEach(box => {
                box.addEventListener('mouseenter', function() {
                    // 隐藏所有元素的arae-box2，显示arae-box1
                    boxa.forEach(b => {
                        b.querySelector('.arae-box1').style.display = 'flex';
                        b.querySelector('.arae-box2').style.display = 'none';
                    });
                    
                    // 显示当前元素的arae-box2，隐藏arae-box1
                    this.querySelector('.arae-box1').style.display = 'none';
                    this.querySelector('.arae-box2').style.display = 'flex';
                });
            });
    }).catch(err=> {
    console.log(err)
})

const arr=document.querySelector('.arae-main1')
axios.post('https://www.zongheng.com/api2/catefine/storeSearch', {
    worksTypes: 0,
    bookType: 0,
    subWorksTypes: 0,
    totalWord: 8,
    serialStatus: 1,
    vip: 0,
    naodongFilter: 1,
    categoryId: 0,
    categoryPid: 0
}).then(res=> {
    // console.log(res.data.result.bookList)
    const mm=res.data.result.bookList
    arr.innerHTML = '';
    for(let i=0;i<5;i++){  
        arr.innerHTML+=`
            <div class="arae-box3">
                    <div class="arae-box11">
                        <div class="area-ti1">${mm[i].name}</div>
                        <div class="arae-dsc1">${mm[i].description}</div>
                    </div>
                    <div class="arae-box21">
                        <img src="${mm[i].picUrl}" alt=""  onclick="ju()">
                        <div class="arae-md3">
                            <div class="arae-md11" onclick="ju()">${mm[i].name}</div>
                            <div class="arae-md21">${mm[i].description}</div>
                        </div>
                    </div>
                </div> 
        `
    }
    const boxess= document.querySelectorAll('.arae-box3');
            
            // 初始状态：第一个元素显示arae-box2，隐藏arae-box1
            if(boxess.length > 0) {
                boxess[0].querySelector('.arae-box11').style.display = 'none';
                boxess[0].querySelector('.arae-box21').style.display = 'flex';
            }
            
            // 为每个元素添加鼠标悬停事件
            boxess.forEach(box => {
                box.addEventListener('mouseenter', function() {
                    // 隐藏所有元素的arae-box2，显示arae-box1
                    boxess.forEach(b => {
                        b.querySelector('.arae-box11').style.display = 'flex';
                        b.querySelector('.arae-box21').style.display = 'none';
                    });
                    
                    // 显示当前元素的arae-box2，隐藏arae-box1
                    this.querySelector('.arae-box11').style.display = 'none';
                    this.querySelector('.arae-box21').style.display = 'flex';
                });
            });
    }).catch(err=> {
    console.log(err)
})

const arrs=document.querySelector('.arae-main2')
axios.post('https://www.zongheng.com/api2/catefine/storeSearch', {
    worksTypes: 0,
    bookType: 0,
    subWorksTypes: 0,
    totalWord: 5,
    serialStatus: 1,
    vip: 0,
    naodongFilter: 1,
    categoryId: 0,
    categoryPid: 0
}).then(res=> {
    // console.log(res.data.result.bookList)
    const mmm=res.data.result.bookList
    arrs.innerHTML = '';
    for(let i=0;i<5;i++){  
        arrs.innerHTML+=`
            <div class="arae-box31">
                    <div class="arae-box111">
                        <div class="area-ti11">${mmm[i].name}</div>
                        <div class="arae-dsc11">${mmm[i].description}</div>
                    </div>
                    <div class="arae-box211">
                        <img src="${mmm[i].picUrl}" alt=""  onclick="ju()">
                        <div class="arae-md31">
                            <div class="arae-md111"  onclick="ju()">${mmm[i].name}</div>
                            <div class="arae-md211">${mmm[i].description}</div>
                        </div>
                    </div>
                </div> 
        `
    }
    const boxesss= document.querySelectorAll('.arae-box31');
            
            // 初始状态：第一个元素显示arae-box2，隐藏arae-box1
            if(boxesss.length > 0) {
                boxesss[0].querySelector('.arae-box111').style.display = 'none';
                boxesss[0].querySelector('.arae-box211').style.display = 'flex';
            }
            
            // 为每个元素添加鼠标悬停事件
            boxesss.forEach(box => {
                box.addEventListener('mouseenter', function() {
                    // 隐藏所有元素的arae-box2，显示arae-box1
                    boxesss.forEach(b => {
                        b.querySelector('.arae-box111').style.display = 'flex';
                        b.querySelector('.arae-box211').style.display = 'none';
                    });
                    
                    // 显示当前元素的arae-box2，隐藏arae-box1
                    this.querySelector('.arae-box111').style.display = 'none';
                    this.querySelector('.arae-box211').style.display = 'flex';
                });
            });
    }).catch(err=> {
    console.log(err)
})

const arrss=document.querySelector('.arae-main3')
axios.post('https://www.zongheng.com/api2/catefine/storeSearch', {
    worksTypes: 0,
    bookType: 0,
    subWorksTypes: 0,
    totalWord: 7,
    serialStatus: 1,
    vip: 0,
    naodongFilter: 1,
    categoryId: 0,
    categoryPid: 0
}).then(res=> {
    // console.log(res.data.result.bookList)
    const n=res.data.result.bookList
    arrss.innerHTML = '';
    for(let i=0;i<5;i++){  
        arrss.innerHTML+=`
            <div class="arae-box311">
                    <div class="arae-box1111">
                        <div class="area-ti111">${n[i].name}</div>
                        <div class="arae-dsc111">${n[i].description}</div>
                    </div>
                    <div class="arae-box2111">
                        <img src="${n[i].picUrl}" alt=""  onclick="ju()">
                        <div class="arae-md311">
                            <div class="arae-md1111" onclick="ju()">${n[i].name}</div>
                            <div class="arae-md2111">${n[i].description}</div>
                        </div>
                    </div>
                </div> 
        `
    }
    const boxen= document.querySelectorAll('.arae-box311');
            
            // 初始状态：第一个元素显示arae-box2，隐藏arae-box1
            if(boxen.length > 0) {
                boxen[0].querySelector('.arae-box1111').style.display = 'none';
                boxen[0].querySelector('.arae-box2111').style.display = 'flex';
            }
            
            // 为每个元素添加鼠标悬停事件
            boxen.forEach(box => {
                box.addEventListener('mouseenter', function() {
                    // 隐藏所有元素的arae-box2，显示arae-box1
                    boxen.forEach(b => {
                        b.querySelector('.arae-box1111').style.display = 'flex';
                        b.querySelector('.arae-box2111').style.display = 'none';
                    });
                    
                    // 显示当前元素的arae-box2，隐藏arae-box1
                    this.querySelector('.arae-box1111').style.display = 'none';
                    this.querySelector('.arae-box2111').style.display = 'flex';
                });
            });
    }).catch(err=> {
    console.log(err)
})


function formatUpdateTime(milliseconds) {
    // 处理无效时间（避免接口返回异常值导致报错）
    if (!milliseconds || isNaN(milliseconds)) return "未知时间";
    
    const time = new Date(milliseconds);
    // 获取各时间部分（月份从0开始，需+1；不足2位补0）
    const year = time.getFullYear();
    const month = String(time.getMonth() + 1).padStart(2, '0');
    const day = String(time.getDate()).padStart(2, '0');
    const hours = String(time.getHours()).padStart(2, '0');
    const minutes = String(time.getMinutes()).padStart(2, '0');
    const seconds = String(time.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function formatNumber(num) {
    if (num >= 100000000) {
        return (num / 100000000).toFixed(2) + '亿';
    } else if (num >= 10000) {
        return (num / 10000).toFixed(0) + '万';
    }
    return num.toFixed(0) + '字'; // 不足1万时显示「XX字」
}

let noti=document.querySelectorAll('.no-ti-le')
const cono=document.querySelector('.no-co')
noti.forEach(item=>{
    item.onclick=function(){
        aa=event.target.dataset.index
        console.log(aa)
         noti.forEach(elem => elem.classList.remove('cur'));
         this.classList.add('cur');
        if(aa==0){
            getlist()
            
        }else{
            getlists()
       
        }

        // console.log(event.target.dataset.index)
        
    }
})

function getlist(){

fetch('https://naodongapi.zongheng.com/planet/updates?level=0').then(res=> res.json()).then(res1=>{
    // console.log(res1.result)
     cono.innerHTML = '';
    res1.result.forEach(item=>{
        cono.innerHTML+=`
            <div class="no-item">
                    <div class="column1">
                        <div class="cell">
                                ${item.categoryName}
                        </div>
                    </div>
                    <div class="column2">
                        <div class="book-ti"  onclick="ju()">
                                ${item.bookName}
                        </div>
                    </div>
                     <div class="column3">
                        <div class="book-1">
                            ${item.newestChapter.title}
                        </div>
                    </div>

                    <div class="column4">
                        <div class="book-11">
                            ${formatNumber(item.wordCount)}
                        </div>
                    </div>
                    <div class="column5">
                        <div class="book-11" onclick='diji(${item.authorId})'>
                           ${item.authorName}
                        </div>
                    </div>
                    <div class="column6">
                        <div class="book-11">
                            ${formatUpdateTime(item.newestChapter.updateTime)}
                        </div>
                    </div>
                </div>
        `
    })

}).catch(err=>{
    console.log(err)
})
}

diji=(id)=>{
    // console.log(id)
    window.location.href = 'naodongxingqiu_author.html?id=' +id
}
getlist()

function getlists(){

fetch('https://naodongapi.zongheng.com/planet/updates?level=1').then(res=> res.json()).then(res1=>{
    console.log(res1.result)
     cono.innerHTML = '';
    res1.result.forEach(item=>{
        cono.innerHTML+=`
            <div class="no-item">
                    <div class="column1">
                        <div class="cell">
                                ${item.categoryName}
                        </div>
                    </div>
                    <div class="column2">
                        <div class="book-ti"  onclick="ju()">
                                ${item.bookName}
                        </div>
                    </div>
                     <div class="column3">
                        <div class="book-1">
                            ${item.newestChapter.title}
                        </div>
                    </div>

                    <div class="column4">
                        <div class="book-11">
                            ${formatNumber(item.wordCount)}
                        </div>
                    </div>
                    <div class="column5">
                        <div class="book-11">
                           ${item.authorName}
                        </div>
                    </div>
                    <div class="column6">
                        <div class="book-11">
                            ${formatUpdateTime(item.newestChapter.updateTime)}
                        </div>
                    </div>
                </div>
        `
    })

}).catch(err=>{
    console.log(err)
})
}
const tt=document.querySelector('.partner-first')
const rr=document.querySelector('.partner-se')
fetch('https://naodongapi.zongheng.com/planet/footer').then(res=> res.json()).then(res1=> {
    // console.log(res1.result.parter)
    res1.result.parter.parterFirst.forEach(item=>{
        tt.innerHTML+=`
            <div class="tt">${item.title}</div>
        `
    })
     res1.result.parter.parterSecond.forEach(item=>{
        rr.innerHTML+=`
            <div class="rr">${item.title}</div>
        `
    })
}).catch(err=>{
    console.log(err)
})

logn=()=>{
    window.location.href='login.html'
}
logn1=()=>{
    window.location.href='bookstock.html'
}
logn2=()=>{
    window.location.href='books.html'
}
to=()=>{
    window.location.href='first.html'
}
to1=()=>{
    window.location.href='index.html'
}
to3=()=>{
    window.location.href='naodongxingqiu_paihang.html'
}



// se=()=>{
//     console.log(event.target.value)
//     to()
// }
to=()=>{
    console.log(9999)
     const inputElement = document.querySelector('.search input');
    const searchText = inputElement.value.trim();
        console.log(searchText);
        inputElement.value = '';
        window.location.href = 'shearh.html?searchText=' + searchText;
}

diji=()=>{
    window.location.href='naodongxingqiu_author.html'
}
ju=()=>{
    console.log(9999)
    window.location.href='detail.html'
}